package com.xl.bigdata.es.index;

import com.xl.bigdata.es.xpack.ESXpackRestHighLevelClient;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;

import java.io.IOException;
import java.util.List;

/**
 * @ClassName DeleteByQueryAPI
 * @Description TODO
 * @Author xl.gao
 * @Date 2022/1/4 13:23
 * @Version
 */
public class DeleteByQueryAPI {

    public static boolean deleteByQueryAPI(RestHighLevelClient client, String index){

        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(index);
        TermQueryBuilder termQueryBuilder = new TermQueryBuilder("citycomple", "广州市");
        deleteByQueryRequest.setQuery(termQueryBuilder);

        deleteByQueryRequest.setBatchSize(1000);
        deleteByQueryRequest.setSlices(12);

        deleteByQueryRequest.setScroll(TimeValue.timeValueMinutes(10));
        deleteByQueryRequest.setTimeout(TimeValue.timeValueMinutes(2));

        deleteByQueryRequest.setRefresh(true);

        try {
            BulkByScrollResponse bulkByScrollResponse = client.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);

            TimeValue took = bulkByScrollResponse.getTook();
            long total = bulkByScrollResponse.getTotal();
            long deleted = bulkByScrollResponse.getDeleted();
            System.out.println("响应时间：(ms)" + took.getMillis() + " 总量：" + total + " 删除数量：" + deleted);
            List<BulkItemResponse.Failure> bulkFailures = bulkByScrollResponse.getBulkFailures();
            if (bulkFailures != null && bulkFailures.size() > 0) {
                System.out.println("失败任务数量：" + bulkFailures.size());
            } else{
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  false;
    }

    public static void main(String[] args) {

        RestHighLevelClient restHighLevelClient = ESXpackRestHighLevelClient.getRestHighLevelClient();


        deleteByQueryAPI(restHighLevelClient, "address_base_02");

        ESXpackRestHighLevelClient.closeRestHighLevelClient();
    }
}
